#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2020, Erik Henriksson
#
# This file is part of the modm project.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# -----------------------------------------------------------------------------

props = {}

class Instance(Module):
    def __init__(self, driver, instance):
        self.driver = driver
        self.instance = int(instance)

    def init(self, module):
        module.name = str(self.instance)
        module.description = "Instance {}".format(self.instance)

    def prepare(self, module, options):
        return True

    def build(self, env):
        device = env[":target"].identifier
        global props
        props["id"] = self.instance
        props["sercom_name"] = self.driver["name"].capitalize()

        env.substitutions = props
        env.outbasepath = "modm/src/modm/platform/uart"

        env.template("uart_hal.hpp.in", "uart_hal_{}.hpp".format(self.instance))
        env.template("uart_hal_impl.hpp.in", "uart_hal_{}_impl.hpp".format(self.instance))
        env.template("uart.hpp.in", "uart_{}.hpp".format(self.instance))
        env.template("uart.cpp.in", "uart_{}.cpp".format(self.instance))


def init(module):
    module.name = ":platform:uart"
    module.description = "Universal Asynchronous Receiver Transmitter (UART)"

def prepare(module, options):
    device = options[":target"]
    if not (device.has_driver("sercom:sam")):
        return False

    module.depends(
        ":architecture:uart",
        ":math:algorithm",
        ":cmsis:device",
        ":platform:gpio",
        ":platform:gclk")

    global props
    drivers = options[":target"].get_all_drivers("sercom")
    for driver in drivers:
        for instance in driver["instance"]:
            module.add_submodule(Instance(driver, instance))

    props["target"] = device.identifier
    return True

def build(env):
    global props
    env.substitutions = props
    env.outbasepath = "modm/src/modm/platform/uart"
    env.template("uart_base.hpp.in")
